import React, { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate } from "react-router-dom";
import axios from "../../api/axios";
import "./Home.css";

// 定义医生数据类型
interface Doctor {
  doctorid: number;
  doctorname: string;
  doctordescword: string;
  doctoradmin: string;
  doctoradministre: string;
  doctorbrowse: string;
  doctorcity: string;
  doctorflag: string;
  doctorgood: string;
  doctoriddoc: string;
  doctorimage: string;
  doctorprice: number;
  doctorstate: string;
  doctortime: string;
  nosocomium: string;
  socoadmin: string;
  sococity: string;
  socodescword: string;
  socoid: number;
  socoimage: string;
  socolv: string;
  socostate: string;
}

// 定义API响应类型
interface DoctorListResponse {
  msg: string;
  total: number;
  data: Doctor[];
}

function Index() {
  const navigate = useNavigate();
  const [canGoBack, setCanGoBack] = useState(false);

  // 科室标签状态管理
  const [activeDepartment, setActiveDepartment] = useState("");

  // 医生列表状态
  const [doctors, setDoctors] = useState<Doctor[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totalCount, setTotalCount] = useState(0);

  const [hasMore, setHasMore] = useState(true); // 是否还有更多数据
  const [page, setPage] = useState(1); // 当前页码

  // 滚动监听相关
  const observerRef = useRef<IntersectionObserver | null>(null);
  const lastDoctorRef = useRef<HTMLDivElement | null>(null);

  // 获取医生列表数据
  const fetchDoctors = async (department?: string, pageNum?: number) => {
    setLoading(true);
    setError(null);

    try {
      const currentPage = pageNum || page;
      const params: Record<string, string> = {
        pageCode: currentPage.toString(),
        pageSize: "5", // 每次获取5条数据
        city: "三门峡市", // 可以根据需要修改
      };

      // 如果选择了科室，添加到请求参数中
      if (department && department !== "更多>" && department !== "") {
        params.admin = department;
      }

      const response = await axios.get<DoctorListResponse>("/doctor/list", {
        params,
      });

      if (response.data.msg === "获取成功") {
        console.log("API返回数据:", response.data.data);
        console.log("API返回总数:", response.data.total);
        console.log("API返回医生数量:", response.data.data.length);
        console.log("请求参数:", params);

        // 确保数据是数组格式
        const doctorData = Array.isArray(response.data.data)
          ? response.data.data
          : [response.data.data];

        if (page === 1) {
          // 第一页，直接设置数据
          setDoctors(doctorData);
        } else {
          // 加载更多，追加数据
          setDoctors((prev) => {
            // 避免重复数据
            const existingIds = new Set(prev.map((d) => d.doctorid));
            const newDoctors = doctorData.filter(
              (d) => !existingIds.has(d.doctorid)
            );
            return [...prev, ...newDoctors];
          });
        }

        setTotalCount(response.data.total);

        // 判断是否还有更多数据
        if (page === 1) {
          // 第一页，检查是否还有更多数据
          setHasMore(
            doctorData.length === 5 && doctorData.length < response.data.total
          );
        } else {
          // 加载更多页面，检查是否还有更多数据
          const totalLoaded = doctors.length + doctorData.length;
          setHasMore(
            doctorData.length === 5 && totalLoaded < response.data.total
          );
          console.log(
            `已加载 ${totalLoaded} 条数据，总共 ${
              response.data.total
            } 条，还有更多: ${totalLoaded < response.data.total}`
          );
        }
      } else {
        console.log("API返回错误:", response.data);
        setError("获取医生列表失败");
      }
    } catch (err: unknown) {
      console.error("获取医生列表失败:", err);
      const errorMessage = err instanceof Error ? err.message : "网络请求失败";
      setError(errorMessage);

      // 如果API请求失败，使用模拟数据作为备用
      console.log("使用备用数据，共5条医生信息");
      setDoctors([
        {
          doctorid: 1,
          doctorname: "涂晓瑜",
          doctordescword:
            "擅长对妇产科常见病、多发病的治疗,特别是妇科内分泌疾患(多囊卵巢综合症、更年期综合症等)的诊断与治疗。",
          doctoradmin: "1",
          doctoradministre: "妇产科",
          doctorbrowse: "11942",
          doctorcity: "东莞市",
          doctorflag: "0",
          doctorgood: "99",
          doctoriddoc: "123456789",
          doctorimage: "https://robohash.org/1?set=set4",
          doctorprice: 15,
          doctorstate: "主治医师",
          doctortime: "98",
          nosocomium: "东莞市第八人民医院",
          socoadmin: "妇科",
          sococity: "东莞市",
          socodescword: "妇产科常见病、多发病的治疗",
          socoid: 1,
          socoimage: "https://robohash.org/1?set=set3",
          socolv: "三级甲等",
          socostate: "公立",
        },
        {
          doctorid: 2,
          doctorname: "王晓玲",
          doctordescword:
            "常规孕检,产前诊断与筛查。各种妇科疾病的治疗,计划生育手术。",
          doctoradmin: "2",
          doctoradministre: "产科",
          doctorbrowse: "13665",
          doctorcity: "辽宁省",
          doctorflag: "0",
          doctorgood: "100",
          doctoriddoc: "123456790",
          doctorimage: "https://robohash.org/2?set=set4",
          doctorprice: 63,
          doctorstate: "副主任医师",
          doctortime: "99",
          nosocomium: "辽宁省妇幼保健院",
          socoadmin: "产科",
          sococity: "辽宁省",
          socodescword: "产科疾病治疗",
          socoid: 2,
          socoimage: "https://robohash.org/2?set=set3",
          socolv: "三级甲等",
          socostate: "公立",
        },
        {
          doctorid: 3,
          doctorname: "李医生",
          doctordescword:
            "专注于儿科常见疾病的诊断与治疗，对儿童生长发育、营养健康、疫苗接种等方面有丰富经验。",
          doctoradmin: "3",
          doctoradministre: "儿科",
          doctorbrowse: "15890",
          doctorcity: "北京市",
          doctorflag: "0",
          doctorgood: "98",
          doctoriddoc: "123456791",
          doctorimage: "https://robohash.org/3?set=set4",
          doctorprice: 45,
          doctorstate: "主治医师",
          doctortime: "97",
          nosocomium: "北京儿童医院",
          socoadmin: "儿科",
          sococity: "北京市",
          socodescword: "儿科疾病治疗",
          socoid: 3,
          socoimage: "https://robohash.org/3?set=set3",
          socolv: "三级甲等",
          socostate: "公立",
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    // 页面加载时获取所有医生数据
    fetchDoctors("", 1);
  }, []); // 只在组件挂载时执行一次

  // 检查是否可以返回上一页
  useEffect(() => {
    setCanGoBack(window.history.length > 1);
  }, []);

  // 清理IntersectionObserver
  useEffect(() => {
    return () => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }
    };
  }, []);

  // 处理科室标签点击
  const handleDepartmentClick = (department: string) => {
    if (department !== "更多>") {
      setActiveDepartment(department);
      // 重置分页状态
      setPage(1);
      setHasMore(true);
      // 立即获取对应科室的数据
      fetchDoctors(department, 1);
    }
  };

  // 加载更多数据
  const loadMore = useCallback(() => {
    if (hasMore && !loading) {
      console.log(`触发加载更多，当前页: ${page}`);
      const nextPage = page + 1;
      setPage(nextPage);
      fetchDoctors(activeDepartment, nextPage);
    }
  }, [hasMore, loading, page, activeDepartment, fetchDoctors]);

  // 设置最后一个医生的ref，用于滚动监听
  const setLastDoctorRef = useCallback(
    (node: HTMLDivElement | null) => {
      if (observerRef.current) {
        observerRef.current.disconnect();
      }

      if (node && hasMore && !loading) {
        observerRef.current = new IntersectionObserver(
          (entries) => {
            if (entries[0].isIntersecting) {
              console.log("最后一个医生进入视口，触发加载更多");
              loadMore();
            }
          },
          {
            threshold: 0.1, // 当10%的元素可见时触发
            rootMargin: "100px", // 提前100px触发，提供更好的用户体验
          }
        );
        observerRef.current.observe(node);
      }

      lastDoctorRef.current = node;
    },
    [hasMore, loading, loadMore]
  );

  // 处理页面导航
  const handleNavigation = (page: string) => {
    switch (page) {
      case "home":
        navigate("/home");
        break;
      case "list":
        navigate("/list");
        break;
      case "user":
        navigate("/user");
        break;
      default:
        break;
    }
  };

  return (
    <div className="home-page">
      {/* 蓝色头部 */}
      <div className="app-header">
        <div className="header-left">
          {canGoBack && (
            <button
              className="back-btn"
              onClick={() => {
                if (window.history.length > 1) {
                  window.history.back();
                } else {
                  // 如果没有历史记录，可以跳转到默认页面
                  navigate("/");
                }
              }}
              title="返回上一页"
            >
              ←
            </button>
          )}
          <span className="app-name">妙手医生</span>
          <span className="app-dot">•</span>
          <span className="app-subtitle">妙手互联网医院</span>
        </div>
        <div className="header-right">
          <span className="header-icon">⋯</span>
          <span className="header-icon">—</span>
          <span className="header-icon">🎯</span>
        </div>
      </div>

      {/* 搜索框 */}
      <div className="search-container">
        <div className="search-box" onClick={() => navigate("/pass")}>
          <span className="search-icon">🔍</span>
          <span className="search-placeholder">
            搜索医生、医院、药品、疾病症状
          </span>
        </div>
      </div>

      {/* 通知横幅 */}
      <div className="notification-banner">
        <span className="notification-icon">📢</span>
        <span className="notification-text">
          为了更好的服务您,即日起您点击医生的"复诊开方"按
        </span>
      </div>

      {/* 功能卡片区域 */}
      <div className="features-section">
        <div className="feature-card">
          <div className="feature-icon">📅</div>
          <div className="feature-title">预约挂号</div>
          <div className="feature-subtitle">30W+专家入驻</div>
        </div>

        <div className="feature-card">
          <div className="feature-icon">
            💬
            <span className="fast-badge">快</span>
          </div>
          <div className="feature-title">极速问诊</div>
          <div className="feature-subtitle">平均3分钟接诊</div>
        </div>

        <div className="feature-card">
          <div className="feature-icon">💊</div>
          <div className="feature-title">复诊开方</div>
          <div className="feature-subtitle">慢病续方送到家</div>
        </div>
      </div>

      {/* 医生问诊区域 */}
      <div className="consultation-section">
        {/* 标题和科室标签 */}
        <div className="consultation-header">
          <div className="title-row">
            <h2 className="consultation-title">我要问专家</h2>
            <span className="more-link">更多{">"}</span>
          </div>
          <div className="department-tabs">
            <div
              className={`tab-item ${activeDepartment === "" ? "active" : ""}`}
              onClick={() => handleDepartmentClick("")}
            >
              全部
            </div>
            <div
              className={`tab-item ${
                activeDepartment === "妇产科" ? "active" : ""
              }`}
              onClick={() => handleDepartmentClick("妇产科")}
            >
              妇产科
            </div>
            <div
              className={`tab-item ${
                activeDepartment === "儿科" ? "active" : ""
              }`}
              onClick={() => handleDepartmentClick("儿科")}
            >
              儿科
            </div>
            <div
              className={`tab-item ${
                activeDepartment === "皮肤科" ? "active" : ""
              }`}
              onClick={() => handleDepartmentClick("皮肤科")}
            >
              皮肤科
            </div>
            <div
              className={`tab-item ${
                activeDepartment === "心血管" ? "active" : ""
              }`}
              onClick={() => handleDepartmentClick("心血管")}
            >
              心血管
            </div>
            <div
              className={`tab-item ${
                activeDepartment === "呼吸内科" ? "active" : ""
              }`}
              onClick={() => handleDepartmentClick("呼吸内科")}
            >
              呼吸内科
            </div>
            <div className="tab-item more">更多{">"}</div>
          </div>
        </div>

        {/* 医生列表 */}
        <div className="doctors-list">
          {/* 调试信息 */}
          <div
            style={{
              padding: "10px",
              background: "#f0f0f0",
              margin: "10px 0",
              fontSize: "12px",
            }}
          >
            当前医生数量: {doctors.length} | API总数: {totalCount} | 加载状态:{" "}
            {loading ? "加载中" : "完成"} | 错误: {error || "无"}
          </div>

          {loading ? (
            <p>加载中...</p>
          ) : error ? (
            <p style={{ color: "red" }}>{error}</p>
          ) : doctors.length === 0 ? (
            <p>暂无医生信息</p>
          ) : (
            doctors.map((doctor, index) => {
              const isLastDoctor = index === doctors.length - 1;
              return (
                <div
                  key={doctor.doctorid}
                  ref={isLastDoctor ? setLastDoctorRef : null}
                  className="doctor-card"
                  onClick={() =>
                    navigate(`/xianqing`, {
                      state: { doctorData: doctor },
                    })
                  }
                  style={{ cursor: "pointer" }}
                >
                  {/* 调试信息 */}
                  <div
                    style={{
                      position: "absolute",
                      top: "5px",
                      right: "5px",
                      background: "red",
                      color: "white",
                      padding: "2px 5px",
                      fontSize: "10px",
                    }}
                  >
                    医生{index + 1} (ID: {doctor.doctorid})
                  </div>
                  {/* 头像 - 左上角 */}
                  <div className="doctor-avatar">
                    {doctor.doctorimage ? (
                      <img
                        src={doctor.doctorimage}
                        alt={`${doctor.doctorname}头像`}
                        onError={(e) => {
                          // 如果图片加载失败，显示默认头像
                          const target = e.target as HTMLImageElement;
                          target.style.display = "none";
                          target.nextElementSibling?.setAttribute(
                            "style",
                            "display: flex"
                          );
                        }}
                      />
                    ) : null}
                    <div
                      className="default-avatar"
                      style={{
                        display: doctor.doctorimage ? "none" : "flex",
                      }}
                    >
                      👩‍⚕️
                    </div>
                  </div>

                  {/* 医生信息 */}
                  <div className="doctor-info">
                    <div className="doctor-details">
                      <div className="doctor-name">
                        {doctor.doctorname} {doctor.doctorstate}
                      </div>
                      <div className="doctor-hospital">
                        {doctor.nosocomium || "未知医院"} (
                        {doctor.doctoradministre || "未知科室"})
                      </div>

                      <div className="consultation-types">
                        <span className="type-tag">图文咨询</span>
                        <span className="type-tag">电话咨询</span>
                      </div>
                      <div className="doctor-expertise">
                        擅长: {doctor.doctordescword}
                        <span className="expand-arrow">▼</span>
                      </div>

                      {/* 显示更多API数据信息 */}
                      <div
                        style={{
                          fontSize: "10px",
                          color: "#666",
                          marginTop: "8px",
                        }}
                      >
                        <div>
                          城市: {doctor.doctorcity} | 科室:{" "}
                          {doctor.doctoradministre}
                        </div>
                        <div>
                          医院等级: {doctor.socolv} | 医院类型:{" "}
                          {doctor.socostate}
                        </div>
                        <div>
                          医生ID: {doctor.doctorid} | 文档ID:{" "}
                          {doctor.doctoriddoc}
                        </div>
                      </div>
                      <div className="doctor-stats">
                        <span className="rating">
                          好评率{doctor.doctorgood}%
                        </span>
                        <span className="separator">|</span>
                        <span className="banners">锦旗{doctor.doctorflag}</span>
                        <span className="separator">|</span>
                        <span className="views">
                          浏览人次{doctor.doctorbrowse}
                        </span>
                      </div>
                      <div className="price-and-button-row">
                        <div className="doctor-price">
                          ¥{doctor.doctorprice}起
                        </div>
                        <button className="ask-doctor-btn">问医生</button>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })
          )}

          {/* 自动加载提示 */}
          {hasMore && doctors.length > 0 && (
            <div className="auto-load-hint">
              {loading ? (
                <div style={{ textAlign: "center", padding: "20px" }}>
                  <div style={{ marginBottom: "10px" }}>
                    🔄 正在加载更多医生...
                  </div>
                  <div style={{ fontSize: "12px", color: "#666" }}>
                    已加载 {doctors.length} 条，总共 {totalCount} 条
                  </div>
                </div>
              ) : (
                <div style={{ textAlign: "center", padding: "20px" }}>
                  <div style={{ marginBottom: "10px" }}>
                    ⬆️ 上滑到底部自动加载更多
                  </div>
                  <div style={{ fontSize: "12px", color: "#666" }}>
                    已加载 {doctors.length} 条，总共 {totalCount} 条
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 为你推荐区域 */}
      <div className="recommendations-section">
        <div className="recommendations-header">
          <h2 className="recommendations-title">为你推荐</h2>
        </div>

        <div className="recommendations-list">
          {/* 推荐内容1 - 问答 */}
          <div className="recommendation-item">
            <div className="recommendation-content">
              <div className="question-header">
                <div className="question-icon">问</div>
                <div className="question-title">抑郁症的原因</div>
              </div>
              <div className="answer-preview">
                抑郁症是一种疾病,不会轻易罹患抑郁症。发病的原因目前还不清楚,可能和遗传因素、社会...
              </div>
              <div className="doctor-info">
                <div className="doctor-avatar-small">👨‍⚕️</div>
                <div className="doctor-name-small">万兴松</div>
                <div className="doctor-title">主任医师</div>
              </div>
            </div>
            <div className="read-count">8.2w 阅读</div>
          </div>

          {/* 推荐内容2 - 问答 */}
          <div className="recommendation-item">
            <div className="recommendation-content">
              <div className="question-header">
                <div className="question-icon">问</div>
                <div className="question-title">高血压能吃黑芝麻糊吗</div>
              </div>
              <div className="answer-preview">
                对于存在高血压的患者是可以食用黑芝麻糊的。由于黑芝麻糊当中富含丰富的钾元素,在某种...
              </div>
              <div className="doctor-info">
                <div className="doctor-avatar-small">👩‍⚕️</div>
                <div className="doctor-name-small">魏晓冬</div>
                <div className="doctor-title">主治医师</div>
              </div>
            </div>
            <div className="read-count">8.8w 阅读</div>
          </div>

          {/* 推荐内容3 - 文章 */}
          <div className="recommendation-item">
            <div className="recommendation-content">
              <div className="question-title">怀孕可以吃甲亢药吗</div>
              <div className="answer-preview">
                甲亢药一般是指治疗甲状腺功能亢进症的药物,怀孕的患者一般可以吃治疗甲状腺功能亢进症的药物,但是...
              </div>
              <div className="content-tag">文章</div>
            </div>
            <div className="read-count">4523阅读</div>
          </div>

          {/* 推荐内容4 - 视频 */}
          <div className="recommendation-item video-item">
            <div className="recommendation-content">
              <div className="question-title">脊髓型颈椎病引发什么症状</div>
              <div className="video-thumbnail">
                <div className="video-overlay">
                  <div className="video-title">脊髓型颈椎病引发什么症状</div>
                  <div className="video-doctor">高 主治医师</div>
                  <div className="video-department">骨科</div>
                  <div className="video-hospital">济宁医学院附属医院</div>
                  <div className="video-duration">01:15</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 底部导航 */}
      <div className="bottom-nav">
        <div
          className="nav-item active"
          onClick={() => handleNavigation("home")}
        >
          <div className="nav-icon">🏠</div>
          <div className="nav-text">首页</div>
        </div>
        <div className="nav-item" onClick={() => handleNavigation("list")}>
          <div className="nav-icon">💬</div>
          <div className="nav-text">消息</div>
        </div>
        <div className="nav-item" onClick={() => handleNavigation("user")}>
          <div className="nav-icon">👤</div>
          <div className="nav-text">我的</div>
        </div>
      </div>
    </div>
  );
}

export default Index;
